﻿/*
 * Last review by   : Yaser
 * Last review date : JUL-25-09 
 */
using System.Collections;
using ERP.Framework.Components.Utilities.TracingHelper;

namespace ERP.Framework.Components.SortingHelper
{
    /// <summary>
    /// Quick sorting
    /// </summary>
    internal abstract class QuickSortHelper
    {
        #region Members

        private const string TRACING_CATEGORY = "ERP.Framework.Components.SortingHelper.QuickSortHelper";

        #endregion

        #region Methods

        /// <summary>
        /// Sorts the list.
        /// </summary>
        /// <param name="array">The array.</param>
        public static void SortList(IList array)
        {
            TraceUtil.Write(TRACING_CATEGORY, "SortList : Start");
            SortList(array, 0, array.Count - 1);
            TraceUtil.Write(TRACING_CATEGORY, "SortList : End");
        }

        /// <summary>
        /// Sorts the list.
        /// </summary>
        /// <param name="array">The array.</param>
        /// <param name="left">The left.</param>
        /// <param name="right">The right.</param>
        private static void SortList(IList array, int left, int right)
        {
            int l_hold, r_hold;
            Comparer comparer = new Comparer(System.Threading.Thread.CurrentThread.CurrentCulture);

            object pivot = array[left];
            l_hold = left;
            r_hold = right;

            while (left < right)
            {
                while ((comparer.Compare(array[right], pivot) >= 0) && (left < right))
                {
                    right--;
                }

                if (left != right)
                {
                    array[left] = array[right];
                    left++;
                }

                while ((comparer.Compare(array[left], pivot) >= 0) && (left < right))
                {
                    left++;
                }

                if (left != right)
                {
                    array[right] = array[left];
                    right--;
                }
            }

            array[left] = pivot;
            int pivotIndex = left;
            left = l_hold;
            right = r_hold;

            if (left < pivotIndex)
            {
                SortList(array, left, pivotIndex - 1);
            }

            if (right > pivotIndex)
            {
                SortList(array, pivotIndex + 1, right);
            }
        }

        #endregion
    }
}
